import {
  ZegoExpressEngine
} from './ZegoExpressMiniProgram-2.6.0.js';
let axios = require("./util.js")
import TIM from './tim-wx.js';
const app = getApp();

let zg;
let tim;
export const IMSDK = (context, res) => {
  // authCheck(context);
  let options = {
    SDKAppID: axios.Decrypt('7BC44F495B024F5633D3F5CD9741BF41') * 1, //账号加密 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID 
  }; 
  // 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
  tim = TIM.create(options); // SDK 实例通常用 tim 表示
  tim.setLogLevel(4); // release 级别，SDK 输出关键信息，生产环境时建议使用
  // tim.on(TIM.EVENT.SDK_READY, function (event) {
  // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
  // event.name - TIM.EVENT.SDK_READY
  // console.log(event);
  // });
  tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, (event) => {
    let arrunreadCount = [];
    let messageList_liaot = [];
    let Sum_ = 0;
    event.data.forEach(item => {
      item.isTouchMove = false;
      messageList_liaot.push(item)
      if (item.unreadCount > 0) {
        arrunreadCount.push(item.conversationID)
        Sum_ += item.unreadCount
      }
    });
    context.setData({
      arrunreadCount: arrunreadCount,
      messageList_liaot: messageList_liaot,
      Sum_: Sum_,
    })
    app.globalData.Sum_ = Sum_;
    setTimeout(() => {
      wx.setStorageSync('messageList_liaot', messageList_liaot)
    }, 1000)

  });
  // tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event) {
  //         // console.log(event);
  // });

  return tim;
}
export const initSDK = (context) => {
  const app = getApp();
  if (!_checkParam(app.globalData.zegoAppID, app.globalData.server)) return false;
  /** 初始化SDK，userID 为用户自定义ID，全局唯一 */
  zg = new ZegoExpressEngine(app.globalData.zegoAppID, app.globalData.server);
  //   console.log('version', zg.getVersion());
  zg.setDebugVerbose(false);
  authCheck(context);
  zg.on("roomStreamUpdate", (roomID, updateType, streamList) => {
    console.log("roomStreamUpdate", roomID, updateType, streamList);
    if (updateType === "ADD") {
      context.setData({
        streamList: streamList
      })
      playAll(streamList, context);
    } else {
      stopPlayAll(streamList, context);
    }
  });
  // the event is triggered when one join or leave the room
  zg.on("roomUserUpdate", (roomID, updateType, userList) => {
    console.log(
      "roomID: ",
      roomID,
      " updateType: ",
      updateType === "ADD" ? "join" : "leave",
      " userList: ",
      userList
    );
    let roomUserList = context.data.roomUserList;
    if (updateType === "DELETE") {
      userList.forEach((user) => {
        const i = roomUserList.findIndex((item) => item.userID === user.userID);
        roomUserList.splice(i, 1);
      });
    } else if (updateType === "ADD") {
      userList.forEach((user) => {
        if (user.userID !== context.data.userID) {
          roomUserList.push(user);
        }
      });
    }
    context.setData({
      roomUserList,
    });
  });
  zg.on("roomStateUpdate", (roomID, state, errorCode, extendedData) => {
    console.log("roomStateUpdate", roomID, state, errorCode, extendedData);
    if (state === "DISCONNECTED") {
      context.setData({
        connectType: 0,
      });
      if (errorCode == 1002050) { //重复登录强制下线
        if(JSON.parse(extendedData).custom_kickout_message == 'Login Repeat'){
          wx.showToast({
            title: '重复登录',
            icon: "none",
            duration: 2000,
          })
          setTimeout(() => {
            wx.clearStorage()
            wx.reLaunch({
              url: '/pages/login/login',
            })
          }, 2000)
        }else {
        wx.showToast({
          title: '被踢出房间',
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          wx.navigateBack({ //返回
            delta: 1
          })
        }, 2000)
      }
    }
  }
    if (state == 'CONNECTED') {
      // 与房间连接成功
      context.setData({
        connectType: 1,
      });
      context.waitList(); //更新麦序
    }
  });
  zg.on("publisherStateUpdate", (result) => {
    // console.error("publishStateUpdate", result);
  });
  //       zg.on("tokenWillExpire", (roomID) => {
  //   console.error("token过期30s", roomID);
  //   // 可以在这里调用 renewToken 接口来更新 token 
  //   zg.renewToken(res.data.result.zego_token)
  //     .then(function (token) {
  //       console.log("更新成功");
  //     })
  //     .catch(function (err) {
  //       console.log("更新失败");
  //     })
  // });
  zg.on("playerStateUpdate", (result) => {
    console.log("playStateUpdate", result);
    if (result.state == "PLAY_REQUESTING") {
      var position;
      context.data.list.userlist.forEach(function (item) {
        if (item.user_id.toString() == result.streamID) {
          position = item.position
        }
      })
      console.log(position);
      context.setData({
        position_mk: position
      })
    } else {
      context.setData({
        position_mk: null
      })
    }
  });
  zg.on("publishQualityUpdate", (streamID, publishStats) => {
    console.log("publishQualityUpdate", streamID, publishStats);
  });
  zg.on("playQualityUpdate", (streamID, playStats) => {
    console.log("playQualityUpdate", streamID, playStats);
  });
  zg.on("roomOnlineUserCountUpdate", (roomID, userCount) => {
    // console.error("roomOnlineUserCountUpdate", roomID, userCount)
  });
  zg.on("recvReliableMessage", (roomID, userCount, trans_type) => {
    console.error("recvReliableMessage", roomID, userCount, trans_type);
  });
  zg.on("tokenWillExpire", (roomID) => {
    console.error("token过期30s", roomID);
    context.Turnonthemicrophone();
    // 可以在这里调用 renewToken 接口来更新 token
    zg.renewToken(context.data.zego_token_new_, roomID)
      .then(function (token) {
        console.log("更新成功");
      })
      .catch(function (err) {
        console.log("更新失败");
      })
  });
  zg.on('IMRecvBroadcastMessage', (roomID, chatData) => {
    //   console.log('222222222222222222222222222222222IMRecvBroadcastMessage', roomID, chatData);
  });
  return zg;
};

export const playAll = async (streamList, context) => {
  console.log("streamList", streamList);
  if (streamList.length === 0) {
    console.log("startPlayingStream, streamList is null");
    return;
  }

  // 获取每个 streamId 对应的拉流 url
  for (let i = 0; i < streamList.length; i++) {
    /** 开始拉流，返回拉流地址 */
    try {
      let {
        streamID,
        url
      } = await zg.startPlayingStream(
        streamList[i].streamID, {
          sourceType: "BGP"
        }
      );
      console.log("streamID", streamID, url);
      setPlayUrl(streamID, url, context);
    } catch (error) {
      console.error("error", error);
    }
  }
};

export const startPush = async (context, publishOption) => {
  const app = getApp();
  try {
    /** 开始推流，返回推流地址 */
    const {
      url
    } = await zg.startPublishingStream(app.globalData.user_id.toString(), publishOption);
    console.info('推流地址startPush', url);
    context.setData({
        livePusherUrl: url,
        livePusher: wx.createLivePusherContext(),
      },
      () => {
        context.data.livePusher.start();
        // 开始推流后，停止从CDN拉流，再从服务器拉流
        // context.data.livePlayerList.forEach(async (livePlayer) => {
        //         try {
        //                 console.log("startPush begin", livePlayer);
        //                 // zg.stopPlayingStream(livePlayer.streamID);
        //                 let { streamID, url } = await zg.startPlayingStream(
        //                         livePlayer.streamID,
        //                         {
        //                                 sourceType: "BGP",
        //                         }
        //                 );
        //                 console.log("startPush end", streamID, url);
        //                 setPlayUrl(streamID, url, context);
        //         } catch (e) {
        //                 console.error("startPlayingStream fail: ", e);
        //         }
        // });
      }
    );
  } catch (error) {
    console.error("error", error);
  }
};

export const setPlayUrl = (streamID, url, context) => {
  const app = getApp();
  if (!url) {
    console.log(">>>[liveroom-room] setPlayUrl, url is null");
    return;
  }
  console.log("setPlayUrl", streamID, url);
  for (let i = 0; i < context.data.livePlayerList.length; i++) {
    if (
      context.data.livePlayerList[i]["streamID"] === streamID &&
      context.data.livePlayerList[i]["url"] === url
    ) {
      console.log(
        ">>>[liveroom-room] setPlayUrl, streamID and url are repeated"
      );
      return;
    }
  }

  let streamInfo = {
    streamID: "",
    url: ""
  };
  let isStreamRepeated = false;

  // 相同 streamID 的源已存在，更新 Url
  for (let i = 0; i < context.data.livePlayerList.length; i++) {
    if (context.data.livePlayerList[i]["streamID"] === streamID) {
      isStreamRepeated = true;
      context.data.livePlayerList[i]["url"] = url;
      break;
    }
  }

  // 相同 streamID 的源不存在，创建新 player
  if (!isStreamRepeated) {
    streamInfo["streamID"] = streamID;
    streamInfo["url"] = url;
    streamInfo["playerContext"] = wx.createLivePlayerContext(streamID);
    context.data.livePlayerList.push(streamInfo);
  }
  app.globalData.livePlayerList = context.data.livePlayerList
  context.setData({
    livePlayerList: context.data.livePlayerList,
  }, () => {
    context.addStreamRefer && context.addStreamRefer();
  });
};

export const stopPlayAll = (streamList, context) => {
  if (streamList.length === 0) {
    console.log("stopPlayAll, streamList is empty");
    return;
  }
  let playStreamList = context.data.livePlayerList;
  for (let i = 0; i < streamList.length; i++) {
    let streamID = streamList[i].streamID;
    zg.stopPlayingStream(streamID);
    // 把远程被删除的流从播放的流列表中删除
    for (let j = 0; j < playStreamList.length; j++) {
      if (playStreamList[j]["streamID"] === streamID) {
        playStreamList.splice(j, 1);
        break;
      }
    }
  }
  context.setData({
    livePlayerList: playStreamList
  });
};

export const authCheck = async (context) => {
  if (!zg) return false;
  const result = await zg.checkSystemRequirements();
  console.log("checkSystemRequirements", result);
  if (result.code === 10001) {
    console.log("result ", result.code);
    wx.showModal({
      title: "提示",
      content: "当前微信版本过低，无法使用该功能，请升级到最新微信版本后再试。",
      showCancel: false,
    });
    context.setData({
      canShow: 0,
    });
  } else if (result.code === 10002) {
    // console.log("result ", result.code);
    //   let hasCamera = false;
    let hasRecord = false;
    //   wx.authorize({
    //           scope: "scope.camera",
    //           success() {
    //                   hasCamera = true;
    //                   context.setData({
    //                           canShow: hasRecord ? 1 : 0,
    //                   });
    //           },
    //           fail() {
    //                   hasCamera = false;
    //                   context.setData({
    //                           canShow: 0,
    //                   });
    //           },
    //   });

    wx.authorize({
      scope: "scope.record",
      success() {
        hasRecord = true;
        context.setData({
          canShow: hasRecord ? 1 : 0,
        });
      },
      fail() {
        hasRecord = false;
        context.setData({
          canShow: 0,
        });
      },
    });
  } else {
    context.setData({
      canShow: 1,
    });
  }
};

export const _checkParam = (zegoAppID, server) => {
  if (!zegoAppID) {
    wx.showToast({
      title: `请在app.js中提供正确的zegoAppID`,
      icon: 'none',
      duration: 5000
    });
    console.error('未设置正确的zegoAppID');
    return false;
  }
  if (!server) {
    wx.showToast({
      title: `请在app.js中提供正确的server`,
      icon: 'none',
      duration: 5000
    });
    console.error('未设置正确的server');
    return false;
  }
  return true;
};
// console.log(axios.Encrypt(1400519982));//tim
// console.log(axios.Decrypt('7BC44F495B024F5633D3F5CD9741BF41'));//解密
